<template>
  <div class="traffic-container">
    <span
    :class="tabIndex === index ? 'traffic-active' : ''"
    v-for="(item, index) in trafficList" :key="item.id"></span>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tabIndex: 0,
      trafficList: [
        {
          name: 'red',
          id: 0
        },
        {
          name: 'green',
          id: 1
        },
        {
          name: 'yellow',
          id: 2
        }
      ]
    }
  },
  mounted() {
    this.trafficFn()
  },
  methods: {
    timeAuto(fn, time) {
      setTimeout(() => {
        fn && fn()
      }, time)
    },
    timeAutoPromise(time) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, time)
      })
    },

    // async 因为他将异步代码变为了同步执行
    async trafficFn() {
      await this.timeAutoPromise(3000)
      this.tabIndex = 1;
      await this.timeAutoPromise(4000)
      this.tabIndex = 2;
      await this.timeAutoPromise(2000)
      this.tabIndex = 0;
      this.trafficFn()
    },

    // trafficFn() {
    //   this.timeAutoPromise(3000)
    //   .then(res => {
    //     this.tabIndex = 1;
    //     return this.timeAutoPromise(4000)
    //     // 在一个.then函数中，执行return.下一个.then方法会接收到这个结果
    //   })
    //   .then(res => {
    //     this.tabIndex = 2;
    //     return this.timeAutoPromise(2000)
    //   })
    //   .then(res => {
    //      this.tabIndex = 0;
    //      this.trafficFn()
    //   })
    // }

    // callback hell 回调地狱
    // trafficFn() {
    //   // callback hell 回调地狱
    //   this.timeAuto(() => {
    //     this.tabIndex = 1;
    //     this.timeAuto(() => {
    //       this.tabIndex = 2;
    //        this.timeAuto(() => {
    //          this.tabIndex = 0;
    //           this.trafficFn()
    //        }, 2000)
    //     }, 4000)
    //   }, 3000)
    // }
  },
}
</script>
<style lang="scss">
  .traffic-container {
    width: 100px;
    display: flex;
    flex-wrap: wrap;
    span {
      width: 88px;
      height: 88px;
      border:1px solid #ccc;
      opacity: .4;
      border-radius: 50%;
        margin: 5px;
      &:nth-child(1) {
        background: red;
      }
      &:nth-child(2) {
        background: green;
      }
      &:nth-child(3) {
        background: orange;
      }
      &.traffic-active {
        opacity: 1;
      }
    }
  }
</style>
